class Solution {
public:
    string reverseWords(string s) {
        int m = s.size() - 1;
        string result;
        while (m >= 0) {
            while (m >= 0 && s[m] == ' ') m--;
            int n = m;
            while (n >= 0 && s[n] != ' ') n--;
            result += s.substr(n + 1, m - n) + " ";
            while (n >= 0 && s[n] == ' ') n--;
            m = n;
        }
        if (!result.empty())
            result.pop_back();
        return result;
    }
};
